package com.towexin.application.websocket.config;

import com.towexin.application.websocket.domain.MessageBody;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionSubscribeEvent;

import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

/**
 * TODO
 *
 * @author Towexin
 * @version 1.0
 * @date 2021/8/11 14:41
 */

@Component
public class SubscribeEventListener implements ApplicationListener<SessionSubscribeEvent> {
    private static final Logger logger = LoggerFactory.getLogger(SubscribeEventListener.class);

    @Autowired
    private SimpMessageSendingOperations simpMessageSendingOperations;

    /**
     * 订阅消息触发事件，调用这个方法
     * StompHeaderAccessor：简单消息传递协议中处理消息头的基类
     *     通过这个类，可以获取消息类型(例如：发布订阅，建立连接断开连接), 会话id等
     */
    @Override
    public void onApplicationEvent(SessionSubscribeEvent sessionSubscribeEvent) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(sessionSubscribeEvent.getMessage());
        logger.info("【SubscribeEventListener订阅事件监听器: 订阅频道】---->"+ headerAccessor.getDestination());

        // 如果订阅了私人频道
        if (Objects.equals(headerAccessor.getDestination(), "/custom/notify/" + Objects.requireNonNull(headerAccessor.getUser()).getName())){
            MessageBody messageBody = new MessageBody();
            messageBody.setFrom("system");;
            messageBody.setContent("系统通知-test");
            messageBody.setTargetUser(Objects.requireNonNull(headerAccessor.getUser()).getName());

            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    try {
                        // 私人频道发送
                        simpMessageSendingOperations.convertAndSendToUser(messageBody.getTargetUser(), "/notify/" + messageBody.getTargetUser(), messageBody);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, 1500);    // 延迟1.5两秒
        }

    }
}
